package com.suxin.netty.protocol;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.UUID;

/**
 * @author Tang
 * @classname MyServerHandler
 * @description [ TODO ]
 * @date 2021/1/11 13:23
 */
public class MySimpleServerHandler extends SimpleChannelInboundHandler<ProtocolMessage> {

    private Integer num = 0;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("服务端接收到如下消息：");
        if (msg instanceof ProtocolMessage) {
            ProtocolMessage message = (ProtocolMessage) msg;
            System.out.println("msg：" + new String(message.getMsg()));
        }
        // 回复消息
        System.out.println("server 回复消息...");
        String str = UUID.randomUUID().toString().replace("-", "");
        ProtocolMessage protocolMessage = new ProtocolMessage();
        protocolMessage.setMsg(str.getBytes());
        protocolMessage.setLen(protocolMessage.getMsg().length);
        ctx.writeAndFlush(protocolMessage);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ProtocolMessage msg) throws Exception {
        System.out.println("server channelRead:--->" + msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }
}